﻿//===============================================================================
// Microsoft patterns & practices Enterprise Library Contribution
// Query Application Block
//===============================================================================

using System.Data;
using System.Configuration;
using System.Collections.Generic;
using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.Manageability;

namespace EntLibContrib.Query.Configuration.Manageability.Queries
{
	/// <summary>
	/// Represents a mapper for <see cref="DataQueryData"/> configuration to Wmi.
	/// </summary>
	public static class DataQueryDataWmiMapper
	{
		#region Public Static Methods
		/// <summary>
		/// Creates the <see cref="DataQuerySetting"/> instances that describe the 
		/// configurationObject.
		/// </summary>
		/// <param name="configurationObject">The configuration object for instances that must be managed.</param>
		/// <param name="wmiSettings">A collection to where the generated WMI objects are to be added.</param>
		public static void GenerateWmiObjects(DataQueryData configurationObject,
																					ICollection<ConfigurationSetting> wmiSettings)
		{
			wmiSettings.Add(new DataQuerySetting(configurationObject,
																					configurationObject.Name,
																					configurationObject.CustomCommandName,
																					configurationObject.ParameterSetName,
																					configurationObject.DatabaseInstanceName,
																					configurationObject.Command,
																					configurationObject.CommandType.ToString()));
		}
		#endregion

		#region Internal Static Methods
		/// <summary>
		/// Registers the WMI types.
		/// </summary>
		internal static void RegisterWmiTypes()
		{
			ManagementEntityTypesRegistrar.SafelyRegisterTypes(typeof(DataQuerySetting));
		}

		/// <summary>
		/// Saves the changes.
		/// </summary>
		/// <param name="setting">The setting.</param>
		/// <param name="sourceElement">The source element.</param>
		/// <returns></returns>
		internal static bool SaveChanges(DataQuerySetting setting,
																		ConfigurationElement sourceElement)
		{
			var element = (DataQueryData)sourceElement;

			element.CustomCommandName = setting.CustomCommandName;
			element.ParameterSetName = setting.ParameterSetName;
			element.DatabaseInstanceName = setting.DatabaseInstanceName;
			element.Command = setting.Command;

			CommandType commandType;
			if (ParseHelper.TryParseEnum<CommandType>(setting.CommandType, out commandType))
				element.CommandType = commandType;

			return true;
		}
		#endregion
	}
}
